var _AppUpdate = {
		jsonUrl:'https://neom.cgnpc.com.cn/smartreport-api/neiosAppUrl/update-t.json?'+(new Date).getTime(),//更新查询地址，必填
		appid:'H594EA035',//appid 必填
		wgtVer:'',//app版本号- 自动获取
		osName:'',//系统类型 - 自动获取
	};
	//_AppUpdate.jsonUrl = ''//测试更新
/**
 * 获取配置相关客户端信息
 * 这段代码是不是可以去掉
 */
_AppUpdate.mkeyconfig = function() {
	try{
		console.log("imei：" + plus.device.imei);
		console.log("imsi：" + plus.device.imsi[0]);
	}catch(err){
		return;
	}
	var phonemodel = [],
		mkeyObj, clientObj;
	var osName = plus.os.name == "Android" ? plus.os.name : "iPhone OS";
	var screensize = plus.screen.resolutionWidth * plus.screen.scale + "*" + plus.screen.resolutionHeight * plus.screen.scale;
	phonemodel.push(osName);
	phonemodel.push(plus.os.version);
	phonemodel.push("2.0");
	phonemodel.push("HELLOMUI");
	phonemodel.push(plus.device.vendor);
	phonemodel.push(plus.device.model);
	clientObj = {
		phonemodel: phonemodel.join("|"),
		MSCID: osName === "Android" ? "Android" : "iPhone",
		imei: osName === "Android" ? plus.device.imei : plus.device.uuid,
		imsi: osName === "Android" ? plus.device.imsi[0] : plus.device.uuid,
		screensize: screensize,
		truescreensize: screensize
	}
	localStorage.setItem("client_info", JSON.stringify(clientObj));
	console.log("client_info：" + JSON.stringify(clientObj));
	localStorage.setItem("phonemodel", phonemodel.join("|"));
	console.log("phonemodel：" + phonemodel.join("|"));
	//uuid参数
	//localStorage.setItem("uuid",clientObj.imei);
	localStorage.setItem("uuid",this.getUuid());
	//操作系统版本  
	localStorage.setItem("OSType",(mui.os.ios)?"ios":"Android");
	var thisApp = this;
	
	//版本号信息
	plus.runtime.getProperty(plus.runtime.appid, function(inf) {
		thisApp.wgtVer = inf.version;
		thisApp.osName = plus.os.name == "Android" ? plus.os.name : "iOS";
		console.log("当前应用版本：" + thisApp.wgtVer);
		console.log("当前操作系统版本：" + thisApp.osName);
		localStorage.setItem("currVersion",thisApp.wgtVer);
	});
}
_AppUpdate.getUuid=function() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid;
}
/**
 * 升级准备操作
 */
_AppUpdate.initUpdate=function(callback){
	var thisApp=this;
	
	// 获取本地应用资源版本号
	plus.runtime.getProperty(plus.runtime.appid, function(inf) {
		thisApp.wgtVer = inf.version;
		thisApp.osName = plus.os.name == "Android" ? plus.os.name : "iOS";
		console.log("当前应用版本：" + thisApp.wgtVer);
		console.log("当前操作系统版本：" + thisApp.osName);
		//获取当前版本检查更新
		thisApp.mkeycheckUpdate(callback);
	});
}
/**
 * mkplus+平台更新
 */
_AppUpdate.mkeycheckUpdate=function(callback){
	var thisApp = this,
	checkur = thisApp.jsonUrl;
	console.log("升级检查地址："+checkur);
	mui.ajax(checkur,{
		data:{
		},
		type:"get",
		success: function(data) {
			console.log("升级配置检查"+JSON.stringify(data));
			//var json = JSON.parse(data);
			thisApp.checkmkJson(data,callback);
		}
	});
}
/**
 * 校验版本呢
 */
_AppUpdate.checkmkJson=function(data,callback){
	var _at = this,
	_data=undefined,
	appidcheck=false;
	
	var new_ver,old_ver;
	
	try{
		_data = data[_at.osName];
		appidcheck = data.appid == _at.appid?true:false;
		old_ver = parseInt(_at.wgtVer.replace(/\./g,''));
		new_ver = parseInt(_data.version.replace(/\./g,''));
	}catch(err){
		callback()
		return;
	}console.log(JSON.stringify(_data));
	if(_data && appidcheck){
		if(old_ver >= new_ver){
			console.log('没有更新 不做处理!');
			//没有更新 不做处理
			//检测是否自动登录操作 根据记住账号key值判断
			callback && callback();
		} else {
			console.log('有检测更新!');
			_at.showUpdateView('');
			//有检测更新
			//可以更新 首先判断是否强制  vforce 1为强制 0为不强制
			if(_data.vforce == 1){
				$(".update_button_cancel").addClass("mui-hidden");
			}
			//更新内容
			var verdesc = '';
			if(_data.title){
				verdesc+=_data.title+'<br>';
			}
			if(Array.isArray(_data.note)){
				_data.note.map(function(item,index){
					verdesc+=(index+1)+'、'+item+'<br>';
				});
			}
			$('#verdesc').html(verdesc);
			$("#current_version").text(_at.wgtVer);
			$("#new_version").text(_data.version);
			
			//是否是wgt更新包
			if(_data.ifwgt==1)
			_at.clickurl = _data.wgtUrl;
			//是否是wgtu更新包
			if(_data.ifforce==1)
			_at.clickurl = _data.wgtuUrl;
			//是否是整包
			if(_data.ifall==1)
			_at.clickurl = _data.url;
			
			_at.htmlurl = _data.url;
			$('.update-gateway-parent').addClass('update-is-visible');
			_at.callback = callback;
			//plus.navigator.closeSplashscreen();
		}
	}else{
		//没有更新 不做处理
		//检测是否自动登录操作 根据记住账号key值判断
		callback && callback();
	}
}
/**
 * 计算百分比
 * @param {Object} num
 * @param {Object} num2
 */
_AppUpdate.percentNum=function(num, num2) { 
    return (Math.round(num / num2 * 100)); //位百分比
}
/**
 * 下载升级包
 */
_AppUpdate.mkdownloadurl=function(url){
	var thisApp = this;
	console.log("下载地址"+url);
	var downloadtask = plus.downloader.createDownload(url,{filename:"_doc/update/"}, function(d,status){
        if (status == 200) { 
            console.log("下载更新成功："+d.filename);
            setTimeout(function(){
				$("#progressNumber").text("正在安装！");
			},300);
            //下载完成后开始安装
            thisApp.mkinstallWgt(d.filename); // 安装wgt包
        } else {
            mui.toast("下载更新失败！");
        }
    });
    //监听下载状态
    downloadtask.addEventListener("statechanged", function(task,status){
    	if(!downloadtask){return;}
    	switch(task.state) {
    		case 1: //开始
    			console.log("开始下载...");
    		break;
    		case 2: //已连接到服务器
    			console.log("链接到服务器...");
    		break;
    		case 3:	//已接收到数据
    			var percent = thisApp.percentNum(task.downloadedSize,task.totalSize);
    			//dhcommom.dhlog("进度..."+percent);
    			mui("#mui-progressbar").progressbar().setProgress(percent);
    			$("#progressNumber").text(percent+"%");
    		break;
    		case 4:	// 下载完成
    			console.log("下载完成...");
    			console.log("总大小..."+task.totalSize);
    		break;
    	}
    } );
    downloadtask.start();
}
/**
 * 安装包安装
 */
_AppUpdate.mkinstallWgt=function(path){
	console.log("安装包路径..."+path);
	plus.runtime.install(path,{force: true},function(){
    	mui.toast("安装更新文件成功！将重启应用！");
    	setTimeout(function(){
			plus.runtime.restart();
		},100);
    },function(e){
        console.log("安装更新文件失败["+e.code+"]："+e.message);
        mui.toast("更新包安装失败，请稍后再试");
//      dhcommom.openWindow(leftbuttonurl,false);
		document.querySelector('#alert').style.display = 'none';
    });
}
_AppUpdate.showUpdateView = function(url){
	var thisApp = this;
	var updatehtml = '\
	<div class="update-gateway"><div id="update_div"class="update_div">\
	<div class="update_title"><img src="../img/update_layer.png"/></div>\
	<div class="mui-scroll-wrapper"style="position: relative;height: 130px;margin-bottom: 10px;">\
	<div id="verdesc"class="mui-scroll"style="color:#636363;text-align: left;font-size: 14px;padding:0px 10px;">\
	</div></div><div class="progress"><div><span id="current_version">\
	</span><span class="progress_center"><span id="progressNumber">0%</span><img src="../../loading/img/banben-3@2x.png"/>\
	</span><span id="new_version"></span></div><div id="mui-progressbar"class="mui-progressbar"style="height: 2px;">\
	<span></span></div></div><div id="button_div"class="button_div"style="font-size: 14px;">\
	<div id="update_button_cancel"class="update_button_cancel" data-url="'+url+'">以后再说</div>\
	<div id="update_button_update"class="update_button_update">立即升级</div></div></div></div>';
	var updatediv = document.createElement('div');
	var updatestyle = document.createElement('link');
	updatestyle.rel = 'stylesheet';
	updatestyle.href = 'css/update.css?'+(new Date).getTime();
	updatediv.className = 'update-gateway-parent';
	updatediv.id = 'alert';
	updatediv.innerHTML = updatehtml;
	document.querySelector('body').appendChild(updatestyle);
	document.querySelector('body').appendChild(updatediv);
	
	//添加按钮事件
	updatediv.addEventListener('tap', function(e) {e.stopPropagation();e.preventDefault();
		var target = e.target;
		for(; target && target !== document; target = target.parentNode) {
			if(target.tagName == 'DIV' && target.id == 'update_button_cancel') {
	//			dhcommom.openWindow(target.getAttribute('data-url'),false);
				document.querySelector('#alert').style.display = 'none';
			}else if(target.tagName == 'DIV' && target.id == 'update_button_update'){
				console.log("升级包地址"+thisApp.clickurl);
				//如果地址中包含wgt 说明为资源更新
				if(thisApp.clickurl.indexOf("wgt") > -1 || ~thisApp.clickurl.indexOf('apk')){
					//直接下载
					thisApp.mkdownloadurl(thisApp.clickurl);
				} else if(thisApp.clickurl.indexOf("https") > -1){
					plus.runtime.openURL(thisApp.clickurl);
				} else {
					plus.runtime.openURL(thisApp.htmlurl);
				}
			}
		} 
	}, false)
	return false;
};